package com.gitee.loyo.interfaces.impl

import com.gitee.loyo.KSQL

class UpdateByID<T: Any>(
    private val obj: T,
    private val primaryKeyName: String,
    private val tableName: String? = null,
    private val selective:Boolean = true,
) : BaseModelSQL<T>() {

    init {
        buildSQL()
    }

    override fun buildSQL() {
        builder.append("update ")
            .append(tableName?:KSQL.nameMappingStrategy.toColumnName(obj.javaClass.simpleName))
            .append(" set ")

        var i = 0
        val pkColumnName = KSQL.nameMappingStrategy.toColumnName(primaryKeyName)
        var pkValue: Any? = null
        eachFields(obj){ columnName, value ->
            if(selective) {
                if (KSQL.nullDetector.isNull(value))
                    return@eachFields
            }
            if(columnName == pkColumnName){
                pkValue = value
            }else{
                if(i++ > 0){
                    builder.append(", ")
                }
                builder.append(columnName).append(" = ?")
                parameters.add(value)
            }
        }
        if(pkValue == null){
            throw UnsupportedOperationException("${obj::class}的主键为空")
        }
        builder.append(" where ").append(pkColumnName).append(" = ?")
        parameters.add(pkValue)
    }

}